package com.cqjtu.education.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.cqjtu.education.entity.Course;
import com.cqjtu.education.entity.ExcelImport;
import com.cqjtu.education.entity.User;
import com.cqjtu.education.dao.UserDao;
import com.cqjtu.education.service.UserService;
import com.cqjtu.education.utils.AliyunOSS;
import com.cqjtu.education.utils.FileTypeEnum;
import com.cqjtu.education.utils.Result;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2022-04-07 13:57:18
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private static final String[] FIELDS = new String[]{"学号", "手机号", "姓名"};

    @Resource
    private UserDao userDao;

    @Resource
    private AliyunOSS aliyunOSS;

    @Override
    public void sendSms(String tel, String code) throws ExecutionException, InterruptedException {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tFZgktdttr4e68wDsjA")
                .accessKeySecret("uKb4fI4xOPkr2kZS50RSwCcjzWFNU1")
                //.securityToken("<your-token>") // use STS token
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-chengdu") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setReadTimeout(Duration.ofSeconds(30))
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder().phoneNumbers(tel).signName("重庆友东科技").templateCode("SMS_257675683").templateParam("{\"code\":\"" + code + "\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }

    @Override
    public String uploadUserImage(String id, MultipartFile file) {
        String cover = aliyunOSS.uploadPublic(file);
        User user = userDao.queryById(id);
        user.setPicture(cover);
        userDao.update(user);
        return cover;
    }

    @Override
    public Result importData(MultipartFile file) throws Exception {
        StringBuilder sb = new StringBuilder();
        List<String> list = new ArrayList<>();
        if (file.isEmpty()) {
            sb.append("上传文件为空！");
            return Result.fail(sb.toString());
        }
        String check = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!FileTypeEnum.XLS.getCode().equals(check) && !FileTypeEnum.XLSX.getCode().equals(check)) {
            sb.append("请上传后缀为xlsx或xls的excel文件！");
            return Result.fail(sb.toString());
        }
        sb.append("插入情况：");
        // 导入对象参数，作为导入对象的规约
        ImportParams params = new ImportParams();
        // 虽然被废弃，但是仍然在使用，如果不设置为null，那么第一列为空则不能读取数据
        params.setKeyIndex(null);
        //设置excel列名校验
        params.setImportFields(FIELDS);
        //开启excel字段规则校验
        params.setNeedVerify(true);
        //需要全局异常捕捉，当不是合法的excel模板会报错
        ExcelImportResult<ExcelImport> objectExcelImportResult = null;
        try {
            objectExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), ExcelImport.class, params);
        } catch (ExcelImportException e) {
            sb.append(e);
            return Result.fail(sb.toString());
        }
        if (objectExcelImportResult.isVerifyFail()) {
            for (ExcelImport e : objectExcelImportResult.getFailList()) {
                list.add("第" + e.getRowNum() + "行：" + e.getErrorMsg());
            }
        }
        for (ExcelImport e : objectExcelImportResult.getList()) {
            if (StringUtils.isEmpty(userDao.isRegister(e.getTel())) && StringUtils.isBlank(userDao.isRegister(e.getTel()))) {
                User user = new User();
                user.setRole("student");
                user.setId(String.valueOf(UUID.randomUUID()));
                user.setIdentityId(e.getIdentityId());
                user.setTel(e.getTel());
                user.setPassword(new Md5Hash(e.getIdentityId().substring(e.getIdentityId().length() - 6), "cqjtu", 10).toString());
                user.setUsername(e.getName());
                user.setRealName(e.getName());
                if (userDao.insert(user) == 0) {
                    list.add("第" + e.getRowNum() + "行插入失败，原因未知！");
                }
            } else {
                e.setErrorMsg("该手机号已注册!");
                list.add("第" + e.getRowNum() + "行：" + e.getErrorMsg());
            }
        }
        if (list.size() == 0) {
            return Result.success(sb.toString());
        }
        return Result.fail(-1, "错误信息", list);
    }

    @Override
    public User queryByTel(String tel) {
        return this.userDao.queryByTel(tel);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param key 主键
     * @return 实例对象
     */
    @Override
    public List<User> fuzzyQuery(String key, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return this.userDao.fuzzyQuery(key, pageNum, pageSize);
    }

    @Override
    public User queryById(String id) {
        return userDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.userDao.deleteById(id) > 0;
    }

    @Override
    public int register(User user) {
        String password = new Md5Hash(user.getPassword(), "cqjtu", 10).toString();
        user.setPassword(password);
        String id = UUID.randomUUID().toString();
        user.setId(id);
        user.setAccount(0.0);
        user.setIntegral(0);
        user.setLastTime(new Date());
        user.setCreateTime(new Date());
        user.setPicture("https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/user_default.jpg");
        user.setRole("student");//默认学生，教师账号由学校发放
        return this.userDao.insert(user);
    }

    @Override
    public int countByKey(String key) {
        return this.userDao.countByKey(key);
    }

    @Override
    public boolean isRegister(String tel) {
        String str = this.userDao.isRegister(tel);
        if (str == null || "".equals(str)) {
            return false;
        }
        return true;
    }

    @Override
    public User login(String tel, String password) {
        password = new Md5Hash(password, "cqjtu", 10).toString();
        return userDao.login(tel, password);
    }

    @Override
    public User changePassword(String id, String password) {
        password = new Md5Hash(password, "cqjtu", 10).toString();
        userDao.changePassword(id, password);
        return userDao.queryById(id);
    }

    @Override
    public List<User> getAllUsers(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return userDao.getAllUsers();
    }


}
